using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Pay.Dto;
using JTZY.Model.Pay;
using JTZY.Service.Pay.IPayService;
using JTZY.Admin.WebApi.Filters;
using JTZY.Model;
using Newtonsoft.Json;
using static JTZY.Common.WxNoticeHelper;
using JTZY.Repository;
using Aliyun.OSS;

//创建时间：2024-12-29
namespace JTZY.Admin.WebApi.Controllers.Pay
{
    /// <summary>
    /// 支付单表
    /// </summary>
    [Verify]
    [Route("pay/Corecmsbillpayments")]
    public class CorecmsbillpaymentsController : BaseController
    {
        /// <summary>
        /// 支付单表接口
        /// </summary>
        private readonly ICorecmsbillpaymentsService _CorecmsbillpaymentsService;
        private readonly IRedisOperationRepository _redisOperationRepository;

        public CorecmsbillpaymentsController(ICorecmsbillpaymentsService CorecmsbillpaymentsService
            , IRedisOperationRepository redisOperationRepository)
        {
            _CorecmsbillpaymentsService = CorecmsbillpaymentsService;
            _redisOperationRepository = redisOperationRepository;

        }

        /// <summary>
        /// 查询支付单表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:list")]
        public IActionResult QueryCorecmsbillpayments([FromQuery] CorecmsbillpaymentsQueryDto parm)
        {
            var response = _CorecmsbillpaymentsService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询支付单表详情
        /// </summary>
        /// <param name="PaymentId"></param>
        /// <returns></returns>
        [HttpGet("{PaymentId}")]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:query")]
        public IActionResult GetCorecmsbillpayments(string PaymentId)
        {
            var response = _CorecmsbillpaymentsService.GetInfo(PaymentId);
            
            var info = response.Adapt<CorecmsbillpaymentsDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加支付单表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:add")]
        [Log(Title = "支付单表", BusinessType = BusinessType.INSERT)]
        public IActionResult AddCorecmsbillpayments([FromBody] CorecmsbillpaymentsDto parm)
        {
            var modal = parm.Adapt<Corecmsbillpayments>().ToCreate(HttpContext);

            var response = _CorecmsbillpaymentsService.AddCorecmsbillpayments(modal);

            return SUCCESS(response);
        }

        /// <summary>
        /// 更新支付单表
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:edit")]
        [Log(Title = "支付单表", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateCorecmsbillpayments([FromBody] CorecmsbillpaymentsDto parm)
        {
            var modal = parm.Adapt<Corecmsbillpayments>().ToUpdate(HttpContext);
            var response = _CorecmsbillpaymentsService.UpdateCorecmsbillpayments(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除支付单表
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete/{ids}")]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:delete")]
        [Log(Title = "支付单表", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteCorecmsbillpayments([FromRoute]string ids)
        {
            var idArr = Tools.SplitAndConvert<string>(ids);

            return ToResponse(_CorecmsbillpaymentsService.Delete(idArr));
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <returns></returns>
        [HttpPost("pay")]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:add")]
        public async Task<IActionResult> Pay([FromBody] PayPost entity)
        {
            //var jm = new WebApiCallBack();
            var userId = HttpContext.GetUId();

            var lockKey = "LOCK_Pay:user_" + userId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = await _redisOperationRepository.LockTakeAsync(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                try
                {
                    if (string.IsNullOrEmpty(entity.orderId))
                    {
                        return ToResponse(ResultCode.FAIL, "没有订单号");
                    }
                    else if (string.IsNullOrEmpty(entity.barCode))
                    {
                        return ToResponse(ResultCode.FAIL, "请扫描条码");
                    }
                     
                    var pm=await _CorecmsbillpaymentsService.Pay(entity.orderId, entity.payment_code, userId, entity.payment_type, entity.barCode);

                    if (pm != null) 
                    {
                        return SUCCESS(pm);

                    }
                    else
                    {
                        return ToResponse(ResultCode.FAIL, "订单不存");

                    }
                    //生成支付单,并发起支付
                    // jm = await _billPaymentsServices.Pay(entity.ids, entity.payment_code, _user.ID, entity.payment_type, entity.@params);
                }
                catch (Exception e)
                {
                    return ToResponse(ResultCode.FAIL, "数据处理异常");

                }
                finally
                {
                    await _redisOperationRepository.LockReleaseAsync(lockKey, lockHolder);
                }
            }
            else
            {
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");
            }
        }

        [HttpPost("queryresult")]
        [ActionPermissionFilter(Permission = "corecmsbillpayments:add")]
        public async Task<IActionResult> QueryResult([FromBody] PayPost entity)
        {
            //var jm = new WebApiCallBack();
            var userId = HttpContext.GetUId();

            var lockKey = "LOCK_Pay:user_" + userId;
            var lockHolder = Guid.NewGuid().ToString("N"); //锁持有者
            var redisUserLock = await _redisOperationRepository.LockTakeAsync(lockKey, lockHolder, TimeSpan.FromSeconds(10));
            if (redisUserLock)
            {
                try
                {
                    if (string.IsNullOrEmpty(entity.orderId))
                    {
                        return ToResponse(ResultCode.FAIL, "没有订单号");
                    }
                    if (string.IsNullOrEmpty(entity.paymentId))
                    {
                        return ToResponse(ResultCode.FAIL, "没有支付订单号");
                    }
                    var pm = await _CorecmsbillpaymentsService.Query(entity.orderId, entity.paymentId, userId, entity.payment_type);

                    if (pm == null)
                    {
                        return SUCCESS(pm);

                    }
                    else
                    {
                        return ToResponse(ResultCode.FAIL, "订单不存");

                    }
                    //生成支付单,并发起支付
                    // jm = await _billPaymentsServices.Pay(entity.ids, entity.payment_code, _user.ID, entity.payment_type, entity.@params);
                }
                catch (Exception e)
                {
                    return ToResponse(ResultCode.FAIL, "数据处理异常");

                }
                finally
                {
                    await _redisOperationRepository.LockReleaseAsync(lockKey, lockHolder);
                }
            }
            else
            {
                return ToResponse(ResultCode.FAIL, "当前请求太频繁_请稍后再试");
            }
        }
    }
}